/*
 * twi_pdca.c
 *
 * Created: 8/19/2011 5:04:57 PM
 *  Author: GrubyGrub
 */ 
#include <avr32/io.h>
#include "compiler.h"
#include "intc.h"
#include "twi.h"
#include "pdca.h"
#include "conf_pdca.h"
#include "twi_pdca.h"








int twi_master_read_dma(volatile avr32_twi_t *twi, const twi_package_t *package)
{
   int status = TWI_SUCCESS;

   if( twi_nack )
    status = TWI_RECEIVE_NACK;  // Previous transaction returns a NACK

  else if(pdca_get_channel_status(TWI_PDCA_CHANNEL) == 1 || twi_is_busy())
    return TWI_BUSY;          // Still transmitting...

  // check argument
  if (package->length == 0)
  {
    return TWI_INVALID_ARGUMENT;
  }

  /*clear all the interrupts in the twi interrupt register*/
  twi->idr = ~0UL;
  twi->sr;
  
  twi_nack = false;
  twi_busy = true;


  // set read mode, slave address and 3 internal address byte length
  twi->mmr = (package->chip << AVR32_TWI_MMR_DADR_OFFSET) |
             ((package->addr_length << AVR32_TWI_MMR_IADRSZ_OFFSET) & AVR32_TWI_MMR_IADRSZ_MASK) |
             (1 << AVR32_TWI_MMR_MREAD_OFFSET);

  // set internal address for remote chip
  twi->iadr = package->addr;
  
  // Set pointer to TWIM instance for IT
  twi_inst = twi; 
  
  /*enable interrupt complete*/
  pdca_enable_interrupt_transfer_complete(TWI_PDCA_CHANNEL);
	
  /*start the transfer*/
  twi->cr = AVR32_TWI_CR_MSEN_MASK;
  twi->cr = AVR32_TWI_START_MASK;
  
  /*start the pdca - should we start the PDCA BEFORE?*/
  pdca_enable(TWI_PDCA_CHANNEL);
  
  
  status = TWI_SUCCESS;

  if( twi_nack )
    status = TWI_RECEIVE_NACK;  // Previous transaction returns a NACK

  else if( twi_tx_nb_bytes )
    return TWI_BUSY;          // Still transmitting...

  return status;
}